import React, { Component } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { resetPassword } from '../service/index';

class ResetPasswordDialog extends Component {
  formRef = React.createRef();
  state = {
    loading: false,
  };

  checkPassword = (rule, value) => {
    if (!value) {
      return Promise.reject('请输入密码');
    } else {
      if (!/^[a-zA-Z0-9]{8,20}$/i.test(value)) {
        return Promise.reject('密码必须为8-20位数字或字母');
      } else {
        return Promise.resolve();
      }
    }
  };

  onOk = async () => {
    try {
      let values = await this.formRef.current.validateFields();
      this.setState({ loading: true });
      await resetPassword(this.props.params.uid, values.password);
      this.setState({ loading: false });
      message.info('重置密码成功！');
      this.props.onOk();
    } catch (e) {
      console.log(e);
    }
  };

  render() {
    const { visible, uid } = this.props.params;
    const layout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
    return (<Modal title='重置密码' width={620}
                   visible={visible}
                   confirmLoading={this.state.loading}
                   destroyOnClose={true}
                   onOk={() => this.onOk()}
                   onCancel={this.props.onCancel}>
      <Form ref={this.formRef} {...layout} initialValues={{uid: uid}}>
        <Form.Item name='uid' noStyle={true}>
          <Input type="hidden"/>
        </Form.Item>
        <Form.Item label="密码" name='password' rules={[{ validator: this.checkPassword }]}>
          <Input autoComplete="off"/>
        </Form.Item>
      </Form>
    </Modal>);
  }
}

export default ResetPasswordDialog;
